﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using SGTLightAccent.Models;
using SGTLightAccent.ViewModel;
using GalaSoft.MvvmLight.Messaging;
using Lite.ExcelLibrary.SpreadSheet;
using System.Windows.Data;
using System.Reflection;
using System.IO;

namespace SGTLightAccent.Views
{
    public partial class Clientes : Page
    {
        private System.Windows.Threading.DispatcherTimer dt;
        public Clientes()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            refrescarPagina();
            dt = new System.Windows.Threading.DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0, 0, 0, 5000); 
            dt.Tick += new EventHandler(TickTock);
            dt.Start();

            
        }
        private void TickTock(object sender, EventArgs e)
        {
            if (WebContext.Current.Authentication.User.Identity.IsAuthenticated)
                refrescarPagina();
            else
            {
                if (dt.IsEnabled)
                    dt.Stop();
            }
        }

        private void refrescarPagina()
        {
            EnvioMensaje txt = new EnvioMensaje("loadDescargaActual");
            Messenger.Default.Send<EnvioMensaje, ClientesViewModel>(txt);
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
             // open file dialog to select an export file.   
            SaveFileDialog sDialog = new SaveFileDialog();
            sDialog.Filter = "Excel Files(*.xls)|*.xls";

            if (sDialog.ShowDialog() == true)
            {

                // create an instance of excel workbook
                Workbook workbook = new Workbook();
                // create a worksheet object
                Worksheet worksheet = new Worksheet("Remitos");

                Int16 ColumnCount = 0;
                Int16 RowCount = 0;

                //Writing Column Names 
                foreach (DataGridColumn dgcol in dataGrid2.Columns)
                {
                    worksheet.Cells[0, ColumnCount] = new Cell(dgcol.Header.ToString());
                    ColumnCount++;
                }

                //Extracting values from grid and writing to excell sheet
                //
                foreach (object data in dataGrid2.ItemsSource)
                {
                    ColumnCount = 0;
                    RowCount++;
                    foreach (DataGridColumn col in dataGrid2.Columns)
                    {

                        string strValue = "";
                        Binding objBinding = null;
                        if (col is DataGridBoundColumn)
                            objBinding = (col as DataGridBoundColumn).Binding;
                        if (col is DataGridTemplateColumn)
                        {
                            //This is a template column... let us see the underlying dependency object
                            DependencyObject objDO = (col as DataGridTemplateColumn).CellTemplate.LoadContent();
                            FrameworkElement oFE = (FrameworkElement)objDO;
                            FieldInfo oFI = oFE.GetType().GetField("TextProperty");
                            if (oFI != null)
                            {
                                if (oFI.GetValue(null) != null)
                                {
                                    if (oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)) != null)
                                        objBinding = oFE.GetBindingExpression((DependencyProperty)oFI.GetValue(null)).ParentBinding;
                                }
                            }
                        }
                        if (objBinding != null)
                        {
                            if (objBinding.Path.Path != "")
                            {
                                PropertyInfo pi = data.GetType().GetProperty(objBinding.Path.Path);
                                if (pi != null) strValue = Convert.ToString(pi.GetValue(data, null));
                            }
                            if (objBinding.Converter != null)
                            {
                                if (strValue != "")
                                    strValue = objBinding.Converter.Convert(strValue, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                                //else
                                //    strValue = objBinding.Converter.Convert(data, typeof(string), objBinding.ConverterParameter, objBinding.ConverterCulture).ToString();
                            }
                        }
                        // writing extracted value in excell cell
                        worksheet.Cells[RowCount, ColumnCount] = new Cell(strValue);
                        
                        ColumnCount++;
                    }


                }

                //add worksheet to workbook
                workbook.Worksheets.Add(worksheet);
                // get the selected file's stream
                Stream sFile = sDialog.OpenFile();
                workbook.Save(sFile);
            }

        }
    }
}
